class Solution
{
public:
    vector<vector<int>> updateMatrix(vector<vector<int>> &mat)
    {
        int m = mat.size();
        int n = mat[0].size();
        vector<vector<int>> result(m, vector<int>(n, m + n));

        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (mat[i][j] == 0)
                {
                    result[i][j] = 0;
                }
                if (i - 1 >= 0)
                {
                    result[i][j] = min(result[i][j], result[i - 1][j] + 1);
                }
                if (j - 1 >= 0)
                {
                    result[i][j] = min(result[i][j], result[i][j - 1] + 1);
                }
            }
        }

        for (int i = m - 1; i >= 0; --i)
        {
            for (int j = n - 1; j >= 0; --j)
            {
                if (i < m - 1)
                {
                    result[i][j] = min(result[i][j], result[i + 1][j] + 1);
                }
                if (j < n - 1)
                {
                    result[i][j] = min(result[i][j], result[i][j + 1] + 1);
                }
            }
        }

        return result;
    }
};